package com.open.ui.skin;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;

import java.lang.reflect.Method;

/**
 * 加载APK主题资源
 * Android加载未安装apk中的资源 https://www.jianshu.com/p/1caabe80ad90
 * apk资源加载：https://blog.csdn.net/u010019468/article/details/73729376
 */
public class LoadSkinResource {

    public static void loadSkinAsync(final Context context, final String dexPath, Object ob) {
        PackageManager mPm = context.getPackageManager();
        PackageInfo mInfo = mPm.getPackageArchiveInfo(dexPath, PackageManager.GET_ACTIVITIES);
        String mPackageName = mInfo.packageName;
        AssetManager assetManager = null;
        try {
            assetManager = AssetManager.class.newInstance();
            // 将资源或宿主的资源，那资源共享就解决了一大半
            Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
            addAssetPath.invoke(assetManager, dexPath);
            Resources superRes = context.getResources();
            Resources skinResource = new Resources(assetManager, superRes.getDisplayMetrics(),
                    superRes.getConfiguration());

            // 测试资源文件
            int identifier = skinResource.getIdentifier("colorPrimaryDark", "color", context.getPackageName());
            int color = skinResource.getColor(identifier);
//            activity.findViewById(android.R.id.content).setBackgroundColor(color);

            // 获取资源包的 attr Theme Style 资源
            int themeIdentifier = skinResource.getIdentifier("TVUITheme.Dark", "style", context.getPackageName());
            Resources.Theme theme1 = skinResource.newTheme();
            theme1.applyStyle(themeIdentifier, true);

//            ColorStateList colorList = SkinManager.getInstance(context).getAttrColorStateList(context, theme1, R.attr.tvui_main_layout_background);
//            view.setBackgroundColor(colorList.getDefaultColor());

            // 设置资源的主题名称，资源, packageName.
            SkinManager.getInstance(context).setSkinName(".Dark");
//            SkinManager.getInstance(context).setResources(skinResource);
//            SkinManager.getInstance(context).setPackageName(mPackageName);
//            SkinManager.getInstance(context).theme = theme1;

            Log.d("hailong.qiu", "loadSkinAsync dexPath:" + dexPath + " skinResource:" + skinResource + " mPackageName:" + mPackageName);
            if (ob != null) {
//                SkinManager.getInstance(context).changeSkin(ob, ".Dark", skinResource);
//                context.setTheme(themeIdentifier);
            }
//            SkinManager.getInstance(context).changeSkin(ob, themeIdentifier, skinResource);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
/*

https://github.com/CankingApp/AndroidTheme

 */